﻿using System.IO;
using System.Linq;

namespace MyWcfRestLib
{
    public class UtilityFunctions
    {
        enum PathStatus
        {
            Invalid = -1,
            NotExists = 0,
            IsDir = 1,
            IsFile = 2
        }

        private static PathStatus CheckPathStatus(string path)
        {
            if (!IsValidPathName(path))
            {
                return PathStatus.Invalid;
            }

            if (Directory.Exists(path))
            {
                return PathStatus.IsDir;
            }

            if (File.Exists(path))
            {
                return PathStatus.IsFile;
            }

            return PathStatus.NotExists;
        }

        public static bool PathExists(string path)
        {
            PathStatus status = UtilityFunctions.CheckPathStatus(path);
            bool exists = ((PathStatus.IsDir == status) || (PathStatus.IsFile == status));
            return exists;
        }

        public static bool IsDir(string path)
        {
            PathStatus status = UtilityFunctions.CheckPathStatus(path);
            bool isDir = ((PathStatus.IsDir == status));
            return isDir;
        }

        public static bool IsValidPathName(string path)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                return false;
            }

            bool isValid = true;
            char[] invalidPathChars = Path.GetInvalidPathChars();
            foreach (char invalidChar in invalidPathChars)
            {
                if (path.Contains(invalidChar))
                {
                    isValid = false;
                    break;
                }
            }

            string fileName = Path.GetFileName(path);
            isValid = !string.IsNullOrWhiteSpace(fileName);

            return isValid;
        }

        public static bool IsValidFileName(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                return false;
            }

            bool isValid = true;
            char[] invalidPathChars = Path.GetInvalidFileNameChars();
            foreach (char invalidChar in invalidPathChars)
            {
                if (name.Contains(invalidChar))
                {
                    isValid = false;
                    break;
                }
            }
            return isValid;
        }
    }
}
